<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>构建四则运算的抽象语法树AST</title>
</head>

<body>

</body>
<script>
  let regexp = /([0-9\.]+)|([ \t]+)|([\r\n]+)|(\*)|(\/)|(\-)|(\+)/g
  let distionary = ["Number", "Whitespace", "LineTerminator", "*", "/", "-", "+"]

  function* tokenSize(source) {
    var result = null;
    var lastIndex = 0;
    do {
      lestIndex = regexp.lastIndex;
      result = regexp.exec(source);
      if (!result) break;

      let token = {
        type: null,
        value: null

      }
      for (var i = 1; i <= distionary.length; i++) {
        if (result[i])
          token.type = distionary[i - 1]
      }
      token.value = result[0]
      yield token;
    } while (result)
    yield {
      type: "EOF"
    }
  }
  let source = [];
  for (let token of tokenSize('10 * 25 / 2')) {
    if (token.type !== "Whitespace" && token.type !== "LineTerminator") {
      source.push(token)
    }
  }

  function Expression(tokens) {}

  function AdditiveExpression(source) {
  }

  function MultiplicativeExpression(source) {
    if (source[0].type === "Number") {
      let node = {
        type: 'MultiplicativeExpression',
        children: [source[0]]
      }
      source[0] = node
      return MultiplicativeExpression(source)
    }
    if (source[0].type === "MultiplicativeExpression" && source[1] && source[1].type === '*') {
      let node = {
        type: 'MultiplicativeExpression',
        operator: '*',
        children: []
      }
      node.children.push(source.shift());
      node.children.push(source.shift());
      node.children.push(source.shift());
      source.unshift(node)
      return MultiplicativeExpression(source)
    }
    if (source[0].type === 'MultiplicativeExpression' && source[1] && source[1].type === '/') {
      let node = {
        type: 'MultiplicativeExpression',
        operator: "/",
        children: []
      }
      node.children.push(source.shift());
      node.children.push(source.shift());
      node.children.push(source.shift());
      source.unshift(node)
      return MultiplicativeExpression(source)
    }
    if (source[0].type = 'MultiplicativeExpression') {
      return source[0]
    }
    return MultiplicativeExpression(source)
  }
  console.log(MultiplicativeExpression(source))
</script>

</html>